{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-ETtu9CvVMDR"
   },
   "source": [
    "<h1>Chapter 7 - langchain-and-langgraph-basic</h1>\n",
    "\n",
    "- Agent 最重要的两个道路：\n",
    "\n",
    "- Prompt Engineering Based Agent System\n",
    "    - 今天我们讲的就是这个 系统怎么构建；\n",
    "- RL 强化学习优化单个模型的能力上限\n",
    "    - 推荐赵老师的 《强化学习数学原理》\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 理解 Langchain Basic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nlangchain                      0.3.25\\nlangchain-core                 0.3.65\\nlangchain-openai               0.3.23\\nlangchain-text-splitters       0.3.8\\nlanggraph                      0.4.8\\nlanggraph-checkpoint           2.0.26\\nlanggraph-prebuilt             0.2.2\\nlanggraph-sdk                  0.1.70\\nlangsmith                      0.3.45\\n'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# %%capture\n",
    "# !pip install langchain\n",
    "\"\"\"\n",
    "langchain                      0.3.25\n",
    "langchain-core                 0.3.65\n",
    "langchain-openai               0.3.23\n",
    "langchain-text-splitters       0.3.8\n",
    "langgraph                      0.4.8\n",
    "langgraph-checkpoint           2.0.26\n",
    "langgraph-prebuilt             0.2.2\n",
    "langgraph-sdk                  0.1.70\n",
    "langsmith                      0.3.45\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 185,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "import os\n",
    "\n",
    "load_dotenv(\".env\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 188,
   "metadata": {},
   "outputs": [],
   "source": [
    "BASE_URL = \"https://api.deepseek.com\"\n",
    "API_KEY = os.environ.get(\"API_KEY\")\n",
    "\n",
    "deepseek_chat_model = \"deepseek-chat\"\n",
    "# deepseek_reason_model = \"deepseek-reasoner\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. langchain, init model;  使用 invoke， 以及 prompt template\n",
    "2. langgraph memory\n",
    "3. langgraph 的 create_react_agent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1 方式1 openai sdk\n",
    "通过 OpenAI sdk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-10-12T08:53:39.270110Z",
     "iopub.status.busy": "2024-10-12T08:53:39.269724Z",
     "iopub.status.idle": "2024-10-12T08:53:39.278516Z",
     "shell.execute_reply": "2024-10-12T08:53:39.277441Z",
     "shell.execute_reply.started": "2024-10-12T08:53:39.270078Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='好的！这里有一个关于电脑的笑话：\\n\\n---\\n\\n**笑话：电脑的抱怨**\\n\\n有一天，一个人对他的电脑说：“你真是太慢了，简直像蜗牛一样！”  \\n电脑冷冷地回复：“嘿，至少我从不‘死机’……哦，等等。”  \\n（屏幕突然蓝屏）  \\n\\n---\\n\\n希望这个笑话能让你笑一笑！如果需要其他类型的笑话，随时告诉我哦！ 😄', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 82, 'prompt_tokens': 11, 'total_tokens': 93, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 11}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': 'bf2db262-2625-4eaf-b579-88ec3921ef91', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--90e2e2b7-4c29-45d3-95af-61ab652d106c-0', usage_metadata={'input_tokens': 11, 'output_tokens': 82, 'total_tokens': 93, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 191,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "llm1 = ChatOpenAI(model=deepseek_chat_model, api_key=API_KEY, base_url=BASE_URL)\n",
    "\n",
    "llm1.invoke([HumanMessage(\"帮我写一个关于 电脑的笑话\")])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 方式2 deepseek\n",
    "使用 deepseek sdk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install -U langchain-deepseek"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是DeepSeek Chat，由深度求索公司（DeepSeek）创造的智能AI助手！🤖✨ 我的使命是帮助你解答问题、提供信息、陪你聊天，甚至帮你处理各种文本和文件内容。无论是学习、工作，还是日常生活中的疑问，我都会尽力帮你解决！😊  \n",
      "\n",
      "有什么我可以帮你的吗？\n"
     ]
    }
   ],
   "source": [
    "# 其他\n",
    "\n",
    "from langchain_deepseek import ChatDeepSeek\n",
    "\n",
    "llm2 = ChatDeepSeek(model=deepseek_chat_model, api_key=API_KEY)\n",
    "messages = [HumanMessage(\"你是谁？\")]\n",
    "print(llm2.invoke(messages).content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 使用 统一的 方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 194,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是DeepSeek Chat，由深度求索公司（DeepSeek）创造的智能AI助手！✨ 我的使命是帮助你解答问题、提供建议、陪你聊天，还能处理各种文本、文档等内容。无论是学习、工作，还是日常生活中的疑问，我都会尽力帮你解决！😊  \n",
      "\n",
      "有什么我可以帮你的吗？\n"
     ]
    }
   ],
   "source": [
    "# pip install -U langchain-deepseek\n",
    "from langchain.chat_models import init_chat_model\n",
    "\n",
    "llm3 = init_chat_model(\n",
    "    deepseek_chat_model, # deepseek-chat\n",
    "    api_key=API_KEY,\n",
    ")\n",
    "print(llm3.invoke(messages).content)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rerbJgwAigbK"
   },
   "source": [
    "# 2. 了解 LangChain Chain"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Wwx2AIuGfCoP"
   },
   "source": [
    "### 2.1 ChatAgent Using LangChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 196,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_template = ChatPromptTemplate(\n",
    "    [\n",
    "        (\"system\", \"you are a helpful assistant\"),\n",
    "        (\"human\", \"帮我写一个和 {topic} 相关的笑话\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['topic']"
      ]
     },
     "execution_count": 197,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt_template.input_variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# llm.invoke(messages)\n",
    "# llm.invoke({\"topic\": \"xxxxx\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content='you are a helpful assistant', additional_kwargs={}, response_metadata={}),\n",
       " HumanMessage(content='帮我写一个和 cat 相关的笑话', additional_kwargs={}, response_metadata={})]"
      ]
     },
     "execution_count": 198,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt_template.invoke({\"topic\": \"cat\"}).to_messages()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "metadata": {
    "id": "ogWsGeg6hElt"
   },
   "outputs": [],
   "source": [
    "# langchain 的 Chain 是什么意思？\n",
    "# A | B | C | D\n",
    "basic_chain = prompt_template | llm2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 200,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "executionInfo": {
     "elapsed": 894,
     "status": "ok",
     "timestamp": 1724338313078,
     "user": {
      "displayName": "Maarten Grootendorst",
      "userId": "11015108362723620659"
     },
     "user_tz": -120
    },
    "id": "KINQxKAINXgG",
    "outputId": "682d6b12-a4aa-4992-8abe-b23334b2a524"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当然！这里有一个和猫有关的笑话：\n",
      "\n",
      "---\n",
      "\n",
      "**笑话：**\n",
      "\n",
      "有一天，一只猫走进了一家酒吧。  \n",
      "酒保看着它问：“你想喝点什么？”  \n",
      "猫想了想说：“给我来一杯‘喵喵白葡萄酒’。”  \n",
      "酒保好奇地问：“这名字挺特别，为什么叫这个？”  \n",
      "猫淡定地回答：“因为每次我喝完，都会‘喵～’地唱起来！”  \n",
      "\n",
      "---\n",
      "\n",
      "希望这个笑话能让你开心！😺\n"
     ]
    }
   ],
   "source": [
    "# Use the chain\n",
    "ans = basic_chain.invoke(\n",
    "    {\n",
    "        \"topic\": \"cat\",\n",
    "    }\n",
    ")\n",
    "print(ans.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sSMBMRxB8gFW"
   },
   "source": [
    "### 2.2 结构化输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Joke(setup='Why did the cat sit on the computer?', punchline='Because it wanted to keep an eye on the mouse!')"
      ]
     },
     "execution_count": 201,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "\n",
    "class Joke(BaseModel):\n",
    "    \"\"\"Joke to tell user.\"\"\"\n",
    "\n",
    "    setup: str = Field(description=\"The setup of the joke\")\n",
    "    punchline: str = Field(description=\"The punchline to the joke\")\n",
    "\n",
    "\n",
    "# 创建 chain\n",
    "joke_chain = prompt_template | llm2.with_structured_output(Joke)\n",
    "\n",
    "# 调用 chain，结构化输出\n",
    "joke_chain.invoke({\"topic\": \"cat\"})\n",
    "\n",
    "# 缺点： FunctionCall 能力的模型才能使用；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 202,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'setup': '为什么猫咪不喜欢玩扑克？', 'punchline': '因为遇到黑猫它们总是输！'}\n"
     ]
    }
   ],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "\n",
    "\n",
    "class Joke(BaseModel):\n",
    "    \"\"\"Joke to tell user.\"\"\"\n",
    "\n",
    "    setup: str = Field(description=\"The setup of the joke\")\n",
    "    punchline: str = Field(description=\"The punchline to the joke\")\n",
    "\n",
    "\n",
    "# 创建包含输出格式要求的提示模板\n",
    "prompt_template = ChatPromptTemplate(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"\"\"你是一个幽默助手。请按照以下JSON格式返回笑话:\n",
    "        {{\n",
    "            \"setup\": \"笑话的铺垫\",\n",
    "            \"punchline\": \"笑话的包袱\"\n",
    "        }}\n",
    "        只返回JSON格式,不要其他内容。\"\"\",\n",
    "        ),\n",
    "        (\"human\", \"帮我写一个和 {topic} 相关的笑话\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "# 创建解析器\n",
    "parser = JsonOutputParser(pydantic_object=Joke)\n",
    "\n",
    "# 创建 chain\n",
    "joke_chain = prompt_template | llm2 | parser\n",
    "\n",
    "# 调用 chain\n",
    "response = joke_chain.invoke({\"topic\": \"cat\"})\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结一下\n",
    "1. 统一的用 init_chat_model / ChatXxxModel 初始化一个 chat model\n",
    "2. 统一的用 invoke(messages)  or invoke({\"topic\": \"xxxx\"})\n",
    "3. 我们可以用 PromptTemplate 构建结构化的 模板\n",
    "4. （不重点），结构化输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7UQ-DZ71P-D-"
   },
   "source": [
    "# 3. LangGraph Memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 204,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = llm2.invoke(messages)\n",
    "\n",
    "# memory \n",
    "# message 以及 output ， 两者要我们自己加起来；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# class MessagesState(TypedDict):\n",
    "#     messages: Annotated[list[AnyMessage], add_messages]\n",
    "\n",
    "# {\n",
    "#     \"messages\": []\n",
    "# }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 206,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "executionInfo": {
     "elapsed": 841,
     "status": "ok",
     "timestamp": 1715331767433,
     "user": {
      "displayName": "Maarten Grootendorst",
      "userId": "11015108362723620659"
     },
     "user_tz": -120
    },
    "id": "-15Eoey5EJUO",
    "outputId": "e475493c-ede1-4932-b954-ade7be05c79a"
   },
   "outputs": [],
   "source": [
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import START, MessagesState, StateGraph\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(state_schema=MessagesState)\n",
    "\n",
    "\n",
    "# Define the function that calls the model\n",
    "def call_model(state: MessagesState):\n",
    "    response = llm2.invoke(state[\"messages\"])\n",
    "    return {\"messages\": response}\n",
    "\n",
    "\n",
    "workflow.add_node(\"node1\", call_model)\n",
    "\n",
    "# Define the (single) node in the graph\n",
    "workflow.add_edge(START, \"node1\")\n",
    "\n",
    "# Add memory\n",
    "memory = MemorySaver()\n",
    "graph = workflow.compile(checkpointer=memory)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 207,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 54
    },
    "executionInfo": {
     "elapsed": 1385,
     "status": "ok",
     "timestamp": 1715331769763,
     "user": {
      "displayName": "Maarten Grootendorst",
      "userId": "11015108362723620659"
     },
     "user_tz": -120
    },
    "id": "N42wQRl-Lykt",
    "outputId": "d1019050-017d-4dcb-a008-7029e9ebd9fe"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Hi Chaofa! 👋 It's great to meet you. How can I assist you today? Whether you have questions, need recommendations, or just want to chat, I'm here to help! 😊  \n",
      "\n",
      "Let me know what's on your mind—maybe a fun fact, a tricky problem, or even your favorite hobby?\n"
     ]
    }
   ],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"abc123\"}}\n",
    "query = \"Hi! I'm chaofa.\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = graph.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()  # output contains all messages in state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 208,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'messages': [HumanMessage(content=\"Hi! I'm chaofa.\", additional_kwargs={}, response_metadata={}, id='5c5441e2-b85f-4522-8a5b-e105ed75c06f'),\n",
       "  AIMessage(content=\"Hi Chaofa! 👋 It's great to meet you. How can I assist you today? Whether you have questions, need recommendations, or just want to chat, I'm here to help! 😊  \\n\\nLet me know what's on your mind—maybe a fun fact, a tricky problem, or even your favorite hobby?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 67, 'prompt_tokens': 10, 'total_tokens': 77, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 10}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': 'f5d1c125-6ec3-4a17-9b45-4d2a2f693f7b', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--c5f75e2e-c1a2-47ff-b437-c9bb5d36bcae-0', usage_metadata={'input_tokens': 10, 'output_tokens': 67, 'total_tokens': 77, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})]}"
      ]
     },
     "execution_count": 208,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Your name is **Chaofa**! 🌟 (I remember because you've mentioned it twice—let me know if you'd prefer a nickname!)  \n",
      "\n",
      "What’s on your mind, Chaofa? 😊\n"
     ]
    }
   ],
   "source": [
    "query = \"What's my name?\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = graph.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I don’t have access to personal information about you unless you share it with me. If you’d like, you can tell me your name, and I’ll be happy to use it in our conversation! 😊\n"
     ]
    }
   ],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"abc345\"}}\n",
    "\n",
    "query = \"What's my name?\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = graph.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BG5sJa1qvS4N"
   },
   "source": [
    "# 4. Agents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.1 Single Agent(With Tool)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 211,
   "metadata": {},
   "outputs": [],
   "source": [
    "# function call 使用和 訓練\n",
    "# https://www.bilibili.com/video/BV1cqdPY8EzT/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 212,
   "metadata": {
    "id": "rcBt8bZM56dM"
   },
   "outputs": [],
   "source": [
    "from langgraph.prebuilt import create_react_agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 213,
   "metadata": {
    "id": "lmRZu8DO2p6k"
   },
   "outputs": [],
   "source": [
    "def add(a: int, b: int) -> int:\n",
    "    \"\"\"Add two numbers\"\"\"\n",
    "    return a + b\n",
    "\n",
    "\n",
    "def multiply(a: int, b: int) -> int:\n",
    "    \"\"\"Multiply two numbers.\"\"\"\n",
    "    return a * b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 214,
   "metadata": {
    "id": "NV-ssNa-4zOK"
   },
   "outputs": [],
   "source": [
    "agent = create_react_agent(\n",
    "    model=ChatDeepSeek(model=deepseek_chat_model, api_key=API_KEY),\n",
    "    tools=[multiply, add],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 215,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = agent.invoke({\"messages\": [HumanMessage(\"帮我计算 1 + 2\")]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 216,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "帮我计算 1 + 2\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  add (call_0_c1d0d208-ae81-4ded-a7ff-4bdb69b74666)\n",
      " Call ID: call_0_c1d0d208-ae81-4ded-a7ff-4bdb69b74666\n",
      "  Args:\n",
      "    a: 1\n",
      "    b: 2\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: add\n",
      "\n",
      "3\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "1 + 2 = 3\n"
     ]
    }
   ],
   "source": [
    "for item in output[\"messages\"]:\n",
    "    item.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "帮我计算 1 * 2\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  multiply (call_0_893cc7fc-8ac8-4012-a6c4-fff050050543)\n",
      " Call ID: call_0_893cc7fc-8ac8-4012-a6c4-fff050050543\n",
      "  Args:\n",
      "    a: 1\n",
      "    b: 2\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: multiply\n",
      "\n",
      "2\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "1 乘以 2 的结果是 2。\n"
     ]
    }
   ],
   "source": [
    "multi_output = agent.invoke({\"messages\": [HumanMessage(\"帮我计算 1 * 2\")]})\n",
    "\n",
    "for item in multi_output[\"messages\"]:\n",
    "    item.pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.2 DeepResearch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install langchain_community\n",
    "# !!pip install -U duckduckgo-search\n",
    "# !!pip install -U langchain-tavily"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### dr 概念理解\n",
    "单一目标执行原则；\n",
    "\n",
    "1. planning agent 做规划，要搜索什么东西；\n",
    "2. search agent，根据 plan 调用 Search tool 检索结果；（可以循环的搜索）\n",
    "3. report agent，只需要写报告；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'query': 'chaofa用代码打点酱油',\n",
       " 'follow_up_questions': None,\n",
       " 'answer': None,\n",
       " 'images': [],\n",
       " 'results': [{'title': 'bbruceyuan (Chaofa Yuan) - GitHub',\n",
       "   'url': 'https://github.com/bbruceyuan',\n",
       "   'content': '博客：https://bruceyuan.com 公众号👏：chaofa用代码打点酱油. bbruceyuan has 25 repositories available. Follow their code on GitHub.',\n",
       "   'score': 0.76554126,\n",
       "   'raw_content': None},\n",
       "  {'title': 'chaofa用代码打点酱油 | Notion',\n",
       "   'url': 'https://chaofa.notion.site/11a569b3ecce49b2826d679f5e2fdb54?v=1550d5d337e68005a0d5000c1d731b37',\n",
       "   'content': 'hi，我是 chaofa，目前是个大模型算法工程师，对于搜索、广告也有我一定的了解~ 这是我的 notion blog. 记录平常的一些学习记录，主要是 paper阅读方面的内容~ 此外会记录一些公开的创作计划; 个人中文博客： chaofa用代码打点酱油 （推荐）',\n",
       "   'score': 0.6506676,\n",
       "   'raw_content': None},\n",
       "  {'title': 'chaofa用代码打点酱油的动态 - 哔哩哔哩',\n",
       "   'url': 'https://www.bilibili.com/opus/987060205629997076',\n",
       "   'content': 'PyTorch手写多头注意力（Multi-Head Self-Attention）-- Self Attention 四重境界 part2（面试常考）',\n",
       "   'score': 0.52962893,\n",
       "   'raw_content': None},\n",
       "  {'title': 'chaofa用代码打点酱油 - YouTube',\n",
       "   'url': 'https://www.youtube.com/@bbruceyuan',\n",
       "   'content': '该频道主要会讲一些大模型相关的分享，让我们一起成长为大佬~欢迎阅读我的博客 bruceyuan.com 获得更好的文字阅读体验，或者',\n",
       "   'score': 0.5195463,\n",
       "   'raw_content': None},\n",
       "  {'title': 'chaofa用代码打点酱油',\n",
       "   'url': 'https://bruceyuan.com/',\n",
       "   'content': '杂谈 chaofa month-summary 深度解读 Kimi-K1.5，真正了解 RL 数据是怎么筛选的 深度解读 Kimi K1.5 论文，介绍其多模态推理模型的技术原理与发展路线，涵盖预训练、监督微调、强化学习及其核心启发，提供详细的算法处理细节和数据构建方法。',\n",
       "   'score': 0.4237686,\n",
       "   'raw_content': None}],\n",
       " 'response_time': 1.72}"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_tavily import TavilySearch\n",
    "\n",
    "search_tool = TavilySearch(\n",
    "    max_results=5, topic=\"general\", tavily_api_key=os.environ.get(\"TAVILY_KEY\")\n",
    ")\n",
    "search_tool.invoke(\"chaofa用代码打点酱油\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 162,
   "metadata": {},
   "outputs": [],
   "source": [
    "# from langchain_core.messages import HumanMessage, SystemMessage\n",
    "# from langgraph.prebuilt import create_react_agent\n",
    "# from typing import List\n",
    "# from pprint import pprint\n",
    "# from langgraph.types import Send\n",
    "\n",
    "# # Create plan agent\n",
    "# plan_prompt = \"\"\"You are a research planner. Break down the research task into specific steps.\n",
    "# Format: List 1-3 key questions to answer.\"\"\"\n",
    "\n",
    "# class QueryAndReason(BaseModel):\n",
    "#     query: str = Field(..., description=\"检索的 Query，需要符合搜索习惯\")\n",
    "#     reason: str = Field(..., description=\"为什么要检索这个 query\")\n",
    "\n",
    "# # Define the structured output format for plan agent\n",
    "# class ResearchPlan(BaseModel):\n",
    "#     \"\"\"Research plan with key questions\"\"\"\n",
    "\n",
    "#     questions: List[QueryAndReason] = Field(\n",
    "#         description=\"List of 1-3 key research questions to investigate.\", max_items=3\n",
    "#     )\n",
    "\n",
    "\n",
    "# plan_agent = ChatDeepSeek(\n",
    "#     model=deepseek_chat_model, api_key=API_KEY\n",
    "# ).with_structured_output(ResearchPlan)\n",
    "\n",
    "\n",
    "# pprint(plan_agent.invoke([HumanMessage(\"write an description about andrej karthy\")]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 217,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "from typing import List\n",
    "from langgraph.graph import START, END\n",
    "\n",
    "# Define the structured output format for plan agent\n",
    "class ResearchPlan(BaseModel):\n",
    "    \"\"\"Research plan with key questions\"\"\"\n",
    "    questions: List[str] = Field(\n",
    "        description=\"List of 1-3 key research questions to investigate\",\n",
    "        max_items=3\n",
    "    )\n",
    "\n",
    "# planner agent 输出 json / markdown （ - [] 第一条要做的事情 -[ ] 第二条要做的事情）\n",
    "# Create plan agent with structured output\n",
    "plan_prompt = \"\"\"You are a research planner. Break down the research task into specific steps.\n",
    "Your response must be a JSON object with a 'questions' field containing 1-3 key research questions.\n",
    "\n",
    "Example format:\n",
    "{\n",
    "    \"questions\": [\n",
    "        \"What is X?\",\n",
    "        \"How does Y work?\",\n",
    "        \"What are the implications of Z?\"\n",
    "    ]\n",
    "}\n",
    "\n",
    "Only return the JSON object, no other text.\"\"\"\n",
    "\n",
    "plan_agent = create_react_agent(\n",
    "    model=ChatDeepSeek(model=deepseek_chat_model, api_key=API_KEY),\n",
    "    tools=[],\n",
    "    prompt=plan_prompt\n",
    ")\n",
    "search_agent = create_react_agent(\n",
    "    model=ChatDeepSeek(model=deepseek_chat_model, api_key=API_KEY),\n",
    "    tools=[search_tool],\n",
    "    prompt=\"you are a helpful assistant. you can search result in search_tool. 当你获得检索结果之后，输出“检索完毕”，必要额外输出任何东西。\",\n",
    ")\n",
    "\n",
    "report_agent = create_react_agent(\n",
    "    model=ChatDeepSeek(model=deepseek_chat_model, api_key=API_KEY),\n",
    "    tools=[],\n",
    "    prompt=\"你是一个擅长写作的人。 你可以根据用户的问题，以及检索的结果，生成一个最终的报告。\"\n",
    ")\n",
    "\n",
    "# plan -> search -> report \n",
    "\n",
    "# Create state graph with custom state\n",
    "class ResearchState(MessagesState):\n",
    "    \"\"\"Custom state that includes research plan\"\"\"\n",
    "    plan: ResearchPlan | None = None\n",
    "\n",
    "# Update workflow with new state\n",
    "workflow = StateGraph(ResearchState)\n",
    "\n",
    "\n",
    "# Add nodes and edges with state transformations\n",
    "workflow.add_node(\"plan_agent\", plan_agent)\n",
    "workflow.add_node(\"search_agent\", search_agent)\n",
    "workflow.add_node(\"report_agent\", report_agent)\n",
    "\n",
    "workflow.add_edge(START, \"plan_agent\")\n",
    "workflow.add_edge(\"plan_agent\", \"search_agent\")\n",
    "workflow.add_edge(\"search_agent\", \"report_agent\")\n",
    "workflow.add_edge(\"report_agent\", END)\n",
    "\n",
    "# Compile workflow\n",
    "app = workflow.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = app.invoke(\n",
    "    {\"messages\": [\n",
    "        HumanMessage(\"write an description about andrej karthy\")\n",
    "    ]}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 174,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'messages': [HumanMessage(content='write an description about andrej karthy', additional_kwargs={}, response_metadata={}, id='6ec66ea6-15f4-4ee5-a70a-8354000a4acc'),\n",
       "  AIMessage(content='```json\\n{\\n    \"questions\": [\\n        \"Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\",\\n        \"What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\",\\n        \"What are some of Andrej Karpathy\\'s most influential projects or publications?\"\\n    ]\\n}\\n```', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 75, 'prompt_tokens': 94, 'total_tokens': 169, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 64}, 'prompt_cache_hit_tokens': 64, 'prompt_cache_miss_tokens': 30}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '00df10ab-adc5-4a2d-bad6-67a1391d03ce', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--1a15fa77-1708-44d4-ae76-54a1ff509d01-0', usage_metadata={'input_tokens': 94, 'output_tokens': 75, 'total_tokens': 169, 'input_token_details': {'cache_read': 64}, 'output_token_details': {}}),\n",
       "  AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_0_9f568643-fc2c-4b87-83f8-24e746141279', 'function': {'arguments': '{\"query\": \"Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\"}', 'name': 'tavily_search'}, 'type': 'function', 'index': 0}, {'id': 'call_1_c86e7717-4d5b-4ba0-a4d7-aea74be2848f', 'function': {'arguments': '{\"query\": \"What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\"}', 'name': 'tavily_search'}, 'type': 'function', 'index': 1}, {'id': 'call_2_c81df54b-e458-4137-800a-b600551eb765', 'function': {'arguments': '{\"query\": \"What are some of Andrej Karpathy\\'s most influential projects or publications?\"}', 'name': 'tavily_search'}, 'type': 'function', 'index': 2}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 112, 'prompt_tokens': 1350, 'total_tokens': 1462, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 1350}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': 'aeba1e3d-5f99-46e9-b7a5-fdd155c3fdcd', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--159fd3cd-a188-4edc-b5de-4d6141213571-0', tool_calls=[{'name': 'tavily_search', 'args': {'query': 'Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?'}, 'id': 'call_0_9f568643-fc2c-4b87-83f8-24e746141279', 'type': 'tool_call'}, {'name': 'tavily_search', 'args': {'query': 'What roles has Andrej Karpathy held at companies like OpenAI and Tesla?'}, 'id': 'call_1_c86e7717-4d5b-4ba0-a4d7-aea74be2848f', 'type': 'tool_call'}, {'name': 'tavily_search', 'args': {'query': \"What are some of Andrej Karpathy's most influential projects or publications?\"}, 'id': 'call_2_c81df54b-e458-4137-800a-b600551eb765', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1350, 'output_tokens': 112, 'total_tokens': 1462, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}),\n",
       "  ToolMessage(content='{\"query\": \"Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy. Bridging the Gap Between Academia and… | by ...\", \"url\": \"https://medium.com/thedeephub/andrej-karpathy-bridging-the-gap-between-academia-and-ai-in-the-real-world-bc55e8649fb8\", \"content\": \"During his Ph.D., Karpathy worked under the guidance of Fei-Fei Li, a prominent figure in AI, and became deeply involved in the development of Convolutional Neural Networks (CNNs), a cornerstone technology in the field of computer vision. After completing his Ph.D. at Stanford, Karpathy emerged as a leading figure in the AI research community, particularly in the domains of deep learning and computer vision. One of Karpathy’s most notable academic contributions was his work on image captioning — teaching AI systems to generate descriptive text for images. Karpathy’s work at Tesla involved deep neural networks, particularly focusing on computer vision. Andrej Karpathy’s educational contributions are notable for their impact on the field of artificial intelligence and machine learning, especially in making complex concepts accessible to a broader audience.\", \"score\": 0.8851659, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - The Education Journey of a Leading AI Expert and ...\", \"url\": \"https://aiforsocialgood.ca/blog/andrej-karpathy-the-education-journey-of-a-leading-ai-expert-and-teslas-director-of-ai\", \"content\": \"Deep Learning and Machine Learning. During his studies, Karpathy devoted significant time and effort to deep learning and machine learning. These disciplines allowed him to develop a deep understanding of how computers can learn and adapt from large amounts of data, paving the way for his notable contributions to the field. Focus on Neural Networks\", \"score\": 0.8116913, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - Wikipedia\", \"url\": \"https://en.wikipedia.org/wiki/Andrej_Karpathy\", \"content\": \"He co-founded and formerly worked at OpenAI,[3][4][5] where he specialized in deep learning and computer vision. [6][7][1][8] Education and early life [edit] Karpathy was born in Bratislava, Czechoslovakia (now Slovakia)[9][10][11][12] and moved with his family to Toronto when he was 15. [13] He completed his Computer Science and Physics bachelor\\'s degrees at University of Toronto in 2009[14] and his master\\'s degree at University of British Columbia in 2011,[14] where he worked on physically-simulated figures (for example, a simulated runner or a simulated person in a crowd) with his adviser Michiel van de Panne. Karpathy received a PhD from Stanford University in 2015 under the supervision of Fei-Fei Li, focusing on the intersection of natural language processing and computer vision, and deep learning models suited for this task.\", \"score\": 0.7471924, \"raw_content\": null}, {\"title\": \"Who is Andrej Karpathy — OpenAI to Tesla & Back - Gold Penguin\", \"url\": \"https://goldpenguin.org/blog/who-is-andrej-karpathy/\", \"content\": \"Published Time: 2024-03-29T04:54:00+00:00 Who is Andrej Karpathy — OpenAI to Tesla & Back | Gold Penguin Gold Penguin ToolsCategoriesBlogGet FeaturedSubmit a Product ToolsCategoriesBlogGet FeaturedSubmit a Product Artificial Intelligence Who is Andrej Karpathy — OpenAI to Tesla & Back Andrej Karpathy is another noteworthy figure in the AI industry who’s played a pivotal role in OpenAI and Tesla. Moreover, the advent of autonomous vehicles wouldn’t be a thing nowadays if not for this one person who’s also worked behind the scenes: Andrej Karpathy. He has worked with OpenAI and Tesla to join them in their AI missions. In this article, we’ll dive into the story of how he started traversing the world of AI from theoretical research to practical application.\", \"score\": 0.7306941, \"raw_content\": null}, {\"title\": \"Andrej Karpathy: The 100 Most Influential People in AI 2024 - TIME\", \"url\": \"https://time.com/7012851/andrej-karpathy/\", \"content\": \"Andrej Karpathy’s name is strewn across the history of modern AI. In 2015, Karpathy, alongside his colleague Professor Fei-Fei Li, designed Stanford University’s first course dedicated to deep-learning, for which he was the primary instructor. “I’m a little bit obsessed with coming to the core of things, ” Karpathy says. His latest venture, Eureka Labs, founded July 2024, aims to build a school that is “AI native.” Its first product will be an undergraduate-level course on AI, designed by a human and guided by an AI teaching assistant. When he first built his AI course at Stanford nine years ago, he was working part-time, and it was done over a few months. Buy your copy of the TIME100 AI issue here\", \"score\": 0.6383174, \"raw_content\": null}], \"response_time\": 2.52}', name='tavily_search', id='1ddfe173-9403-4a00-946e-8e44c99d490b', tool_call_id='call_0_9f568643-fc2c-4b87-83f8-24e746141279'),\n",
       "  ToolMessage(content='{\"query\": \"What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy Departs From OpenAI to Pursue Personal Projects\", \"url\": \"https://www.cryptopolitan.com/andrej-karpathy-parts-ways-with-openai/\", \"content\": \"Andrej Karpathy has left OpenAI to focus on personal projects. He previously played a key role in AI development at Tesla and has been a significant figure in the AI community. ... Before his latest tenure at OpenAI, Karpathy held a pivotal role at Tesla, where he was instrumental in advancing the electric vehicle giant\\'s AI capabilities\", \"score\": 0.9039154, \"raw_content\": null}, {\"title\": \"6 A.I. Startups Backed by OpenAI Co-Founder Andrej Karpathy - Observer\", \"url\": \"https://observer.com/2025/02/openai-cofounder-andrej-karpathy-ai-startups/\", \"content\": \"As one of OpenAI\\'s 11 co-founders, he played a key role in developing the GPT model before leaving in 2017 to lead Tesla\\'s Autopilot effort. He returned to OpenAI in February 2023 as a\", \"score\": 0.85216236, \"raw_content\": null}, {\"title\": \"Who is Andrej Karpathy — OpenAI to Tesla & Back - Gold Penguin\", \"url\": \"https://goldpenguin.org/blog/who-is-andrej-karpathy/\", \"content\": \"Before Karpathy\\'s Affair with OpenAI and Tesla. Andrej first found his place in academia, then into the divisions of Google. Here are the things that he\\'s done prior to his OpenAI-Tesla ventures while in his Stanford and Google era, and everything in between. His Role in Google Brain, Research, and DeepMind\", \"score\": 0.85097736, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - The AI Champion. - LinkedIn\", \"url\": \"https://www.linkedin.com/pulse/andrej-karpathy-ai-champion-serviots-tianf\", \"content\": \"After leaving Tesla in 2022, Karpathy returned to OpenAI in 2023 to lead a small team focused on improving GPT-4 and ChatGPT. However, his current passion lies in AI-driven education and fostering\", \"score\": 0.8443195, \"raw_content\": null}, {\"title\": \"The Professional Journey of Andrej Karpathy - Perplexity\", \"url\": \"https://www.perplexity.ai/page/the-professional-journey-of-an-OvR1nmNIQNS5gJPAtPMk5w\", \"content\": \"Andrej Karpathy\\'s association with OpenAI has been marked by two distinct periods of involvement, each contributing significantly to the organization\\'s development in artificial intelligence. Initially joining as one of the founding members, Karpathy played a pivotal role in the early stages of OpenAI, helping to establish its reputation as a\", \"score\": 0.7407191, \"raw_content\": null}], \"response_time\": 1.74}', name='tavily_search', id='d33ab955-6983-4985-a30e-67ad9f3cceee', tool_call_id='call_1_c86e7717-4d5b-4ba0-a4d7-aea74be2848f'),\n",
       "  ToolMessage(content='{\"query\": \"What are some of Andrej Karpathy\\'s most influential projects or publications?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy: The 100 Most Influential People in AI 2024 - TIME\", \"url\": \"https://time.com/7012851/andrej-karpathy/\", \"content\": \"Andrej Karpathy’s name is strewn across the history of modern AI. In 2015, Karpathy, alongside his colleague Professor Fei-Fei Li, designed Stanford University’s first course dedicated to deep-learning, for which he was the primary instructor. “I’m a little bit obsessed with coming to the core of things, ” Karpathy says. His latest venture, Eureka Labs, founded July 2024, aims to build a school that is “AI native.” Its first product will be an undergraduate-level course on AI, designed by a human and guided by an AI teaching assistant. When he first built his AI course at Stanford nine years ago, he was working part-time, and it was done over a few months. Buy your copy of the TIME100 AI issue here\", \"score\": 0.70483154, \"raw_content\": null}, {\"title\": \"Andrej Karpathy\\'s research works | Stanford University, CA (SU) and ...\", \"url\": \"https://www.researchgate.net/scientific-contributions/Andrej-Karpathy-70761057\", \"content\": \"Andrej Karpathy\\'s 14 research works with 53,299 citations and 32,220 reads, including: PixelCNN++: Improving the PixelCNN with Discretized Logistic Mixture Likelihood and Other Modifications\", \"score\": 0.62633044, \"raw_content\": null}, {\"title\": \"\\u202aAndrej Karpathy\\u202c - \\u202aGoogle Scholar\\u202c\", \"url\": \"https://scholar.google.com/citations?user=l8WuQJgAAAAJ&hl=en\", \"content\": \"Andrej Karpathy. Computer Science PhD student, Stanford University. Verified email at cs.stanford.edu - Homepage. Machine Learning Computer Vision Artificial Intelligence. ... A Karpathy, S Miller, L Fei-Fei. 2013 IEEE International Conference on Robotics and Automation, 2088-2095, 2013. 230:\", \"score\": 0.5654673, \"raw_content\": null}, {\"title\": \"Unlock Genius: Dive Into Andrej Karpathy\\'s Top 8 Mind ... - Medium\", \"url\": \"https://medium.com/@Reviewbooks/unlock-genius-dive-into-andrej-karpathys-top-8-mind-blowing-book-picks-7458dcbef3b1\", \"content\": \"Why is Andrej Karpathy so famous? Andrej Karpathy has gained widespread recognition for his significant contributions to the field of artificial intelligence (AI), particularly in the development\", \"score\": 0.49538648, \"raw_content\": null}, {\"title\": \"Andrej Karpathy\", \"url\": \"https://karpathy.ai/\", \"content\": \"2024 - I started Eureka Labs, a new AI+Education company. Meanwhile, I also make educational videos on AI on my YouTube channel. General audience track: Deep Dive into LLMs like ChatGPT is on under-the hood fundamentals of LLMs. 2017 - 2022 I was the Sr. Director of AI at Tesla, where I led the computer vision team of Tesla Autopilot. This includes in-house data labeling, neural network training, the science of making it work, and deployment in production running on our custom inference chip.\", \"score\": 0.40967003, \"raw_content\": null}], \"response_time\": 2.13}', name='tavily_search', id='6c5a6a9c-cd28-4f49-8fd9-a8a2be6f9cef', tool_call_id='call_2_c81df54b-e458-4137-800a-b600551eb765'),\n",
       "  AIMessage(content='检索完毕', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 2, 'prompt_tokens': 4054, 'total_tokens': 4056, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 1344}, 'prompt_cache_hit_tokens': 1344, 'prompt_cache_miss_tokens': 2710}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '9459ef60-f220-4b23-956e-00923f12ad6b', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--d50f2bb9-5e92-499b-aa86-67bbcf79bf02-0', usage_metadata={'input_tokens': 4054, 'output_tokens': 2, 'total_tokens': 4056, 'input_token_details': {'cache_read': 1344}, 'output_token_details': {}}),\n",
       "  AIMessage(content=\"# Andrej Karpathy: AI Visionary and Innovator\\n\\n## Who is Andrej Karpathy?\\n\\nAndrej Karpathy is a leading figure in artificial intelligence and machine learning, known for his significant contributions to deep learning, computer vision, and autonomous systems. Born in Bratislava (now Slovakia), he moved to Toronto at age 15 and completed his education in computer science and physics at the University of Toronto, followed by a master's at the University of British Columbia and a PhD at Stanford University under AI pioneer Fei-Fei Li.\\n\\n## Notable Contributions\\n\\nKarpathy has made several groundbreaking contributions to AI:\\n\\n- **Convolutional Neural Networks (CNNs)**: Worked on advancing this cornerstone technology in computer vision during his PhD\\n- **Image Captioning**: Developed AI systems capable of generating descriptive text for images\\n- **Deep Learning Education**: Co-designed Stanford University's first deep learning course in 2015 with Fei-Fei Li\\n- **Autonomous Vehicles**: Advanced Tesla's Autopilot capabilities through deep neural networks\\n\\n## Professional Roles\\n\\nKarpathy has held key positions at major technology companies:\\n\\n- **OpenAI**: \\n  - Co-founded OpenAI and specialized in deep learning and computer vision\\n  - Returned in 2023 to lead a team improving GPT-4 and ChatGPT\\n- **Tesla**: \\n  - Served as Senior Director of AI (2017-2022)\\n  - Led Tesla's computer vision team for Autopilot\\n  - Oversaw in-house data labeling, neural network training, and production deployment\\n\\n## Influential Projects and Publications\\n\\nKarpathy's most impactful work includes:\\n\\n- **Stanford's Deep Learning Course**: Pioneering curriculum that educated thousands in AI\\n- **PixelCNN++**: Improved image generation model with discretized logistic mixture likelihood\\n- **Autonomous Driving Systems**: Developed Tesla's vision-based self-driving technology\\n- **Eureka Labs**: His newest venture (founded 2024) creating AI-native education solutions\\n\\nWith over 53,000 citations for his research works, Karpathy continues to shape the AI field through both technical innovation and education. His current focus includes AI-driven learning platforms that combine human expertise with AI teaching assistants.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 457, 'prompt_tokens': 2817, 'total_tokens': 3274, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 2817}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': 'badc381f-6e4a-40a3-b5df-c04884b9314b', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--7cbdff1a-2da8-413d-b2e2-05a15759b9bc-0', usage_metadata={'input_tokens': 2817, 'output_tokens': 457, 'total_tokens': 3274, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})]}"
      ]
     },
     "execution_count": 174,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "write an description about andrej karthy\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "```json\n",
      "{\n",
      "    \"questions\": [\n",
      "        \"Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\",\n",
      "        \"What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\",\n",
      "        \"What are some of Andrej Karpathy's most influential projects or publications?\"\n",
      "    ]\n",
      "}\n",
      "```\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  tavily_search (call_0_9f568643-fc2c-4b87-83f8-24e746141279)\n",
      " Call ID: call_0_9f568643-fc2c-4b87-83f8-24e746141279\n",
      "  Args:\n",
      "    query: Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\n",
      "  tavily_search (call_1_c86e7717-4d5b-4ba0-a4d7-aea74be2848f)\n",
      " Call ID: call_1_c86e7717-4d5b-4ba0-a4d7-aea74be2848f\n",
      "  Args:\n",
      "    query: What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\n",
      "  tavily_search (call_2_c81df54b-e458-4137-800a-b600551eb765)\n",
      " Call ID: call_2_c81df54b-e458-4137-800a-b600551eb765\n",
      "  Args:\n",
      "    query: What are some of Andrej Karpathy's most influential projects or publications?\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search\n",
      "\n",
      "{\"query\": \"Who is Andrej Karpathy and what are his notable contributions in the field of AI and machine learning?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy. Bridging the Gap Between Academia and… | by ...\", \"url\": \"https://medium.com/thedeephub/andrej-karpathy-bridging-the-gap-between-academia-and-ai-in-the-real-world-bc55e8649fb8\", \"content\": \"During his Ph.D., Karpathy worked under the guidance of Fei-Fei Li, a prominent figure in AI, and became deeply involved in the development of Convolutional Neural Networks (CNNs), a cornerstone technology in the field of computer vision. After completing his Ph.D. at Stanford, Karpathy emerged as a leading figure in the AI research community, particularly in the domains of deep learning and computer vision. One of Karpathy’s most notable academic contributions was his work on image captioning — teaching AI systems to generate descriptive text for images. Karpathy’s work at Tesla involved deep neural networks, particularly focusing on computer vision. Andrej Karpathy’s educational contributions are notable for their impact on the field of artificial intelligence and machine learning, especially in making complex concepts accessible to a broader audience.\", \"score\": 0.8851659, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - The Education Journey of a Leading AI Expert and ...\", \"url\": \"https://aiforsocialgood.ca/blog/andrej-karpathy-the-education-journey-of-a-leading-ai-expert-and-teslas-director-of-ai\", \"content\": \"Deep Learning and Machine Learning. During his studies, Karpathy devoted significant time and effort to deep learning and machine learning. These disciplines allowed him to develop a deep understanding of how computers can learn and adapt from large amounts of data, paving the way for his notable contributions to the field. Focus on Neural Networks\", \"score\": 0.8116913, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - Wikipedia\", \"url\": \"https://en.wikipedia.org/wiki/Andrej_Karpathy\", \"content\": \"He co-founded and formerly worked at OpenAI,[3][4][5] where he specialized in deep learning and computer vision. [6][7][1][8] Education and early life [edit] Karpathy was born in Bratislava, Czechoslovakia (now Slovakia)[9][10][11][12] and moved with his family to Toronto when he was 15. [13] He completed his Computer Science and Physics bachelor's degrees at University of Toronto in 2009[14] and his master's degree at University of British Columbia in 2011,[14] where he worked on physically-simulated figures (for example, a simulated runner or a simulated person in a crowd) with his adviser Michiel van de Panne. Karpathy received a PhD from Stanford University in 2015 under the supervision of Fei-Fei Li, focusing on the intersection of natural language processing and computer vision, and deep learning models suited for this task.\", \"score\": 0.7471924, \"raw_content\": null}, {\"title\": \"Who is Andrej Karpathy — OpenAI to Tesla & Back - Gold Penguin\", \"url\": \"https://goldpenguin.org/blog/who-is-andrej-karpathy/\", \"content\": \"Published Time: 2024-03-29T04:54:00+00:00 Who is Andrej Karpathy — OpenAI to Tesla & Back | Gold Penguin Gold Penguin ToolsCategoriesBlogGet FeaturedSubmit a Product ToolsCategoriesBlogGet FeaturedSubmit a Product Artificial Intelligence Who is Andrej Karpathy — OpenAI to Tesla & Back Andrej Karpathy is another noteworthy figure in the AI industry who’s played a pivotal role in OpenAI and Tesla. Moreover, the advent of autonomous vehicles wouldn’t be a thing nowadays if not for this one person who’s also worked behind the scenes: Andrej Karpathy. He has worked with OpenAI and Tesla to join them in their AI missions. In this article, we’ll dive into the story of how he started traversing the world of AI from theoretical research to practical application.\", \"score\": 0.7306941, \"raw_content\": null}, {\"title\": \"Andrej Karpathy: The 100 Most Influential People in AI 2024 - TIME\", \"url\": \"https://time.com/7012851/andrej-karpathy/\", \"content\": \"Andrej Karpathy’s name is strewn across the history of modern AI. In 2015, Karpathy, alongside his colleague Professor Fei-Fei Li, designed Stanford University’s first course dedicated to deep-learning, for which he was the primary instructor. “I’m a little bit obsessed with coming to the core of things, ” Karpathy says. His latest venture, Eureka Labs, founded July 2024, aims to build a school that is “AI native.” Its first product will be an undergraduate-level course on AI, designed by a human and guided by an AI teaching assistant. When he first built his AI course at Stanford nine years ago, he was working part-time, and it was done over a few months. Buy your copy of the TIME100 AI issue here\", \"score\": 0.6383174, \"raw_content\": null}], \"response_time\": 2.52}\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search\n",
      "\n",
      "{\"query\": \"What roles has Andrej Karpathy held at companies like OpenAI and Tesla?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy Departs From OpenAI to Pursue Personal Projects\", \"url\": \"https://www.cryptopolitan.com/andrej-karpathy-parts-ways-with-openai/\", \"content\": \"Andrej Karpathy has left OpenAI to focus on personal projects. He previously played a key role in AI development at Tesla and has been a significant figure in the AI community. ... Before his latest tenure at OpenAI, Karpathy held a pivotal role at Tesla, where he was instrumental in advancing the electric vehicle giant's AI capabilities\", \"score\": 0.9039154, \"raw_content\": null}, {\"title\": \"6 A.I. Startups Backed by OpenAI Co-Founder Andrej Karpathy - Observer\", \"url\": \"https://observer.com/2025/02/openai-cofounder-andrej-karpathy-ai-startups/\", \"content\": \"As one of OpenAI's 11 co-founders, he played a key role in developing the GPT model before leaving in 2017 to lead Tesla's Autopilot effort. He returned to OpenAI in February 2023 as a\", \"score\": 0.85216236, \"raw_content\": null}, {\"title\": \"Who is Andrej Karpathy — OpenAI to Tesla & Back - Gold Penguin\", \"url\": \"https://goldpenguin.org/blog/who-is-andrej-karpathy/\", \"content\": \"Before Karpathy's Affair with OpenAI and Tesla. Andrej first found his place in academia, then into the divisions of Google. Here are the things that he's done prior to his OpenAI-Tesla ventures while in his Stanford and Google era, and everything in between. His Role in Google Brain, Research, and DeepMind\", \"score\": 0.85097736, \"raw_content\": null}, {\"title\": \"Andrej Karpathy - The AI Champion. - LinkedIn\", \"url\": \"https://www.linkedin.com/pulse/andrej-karpathy-ai-champion-serviots-tianf\", \"content\": \"After leaving Tesla in 2022, Karpathy returned to OpenAI in 2023 to lead a small team focused on improving GPT-4 and ChatGPT. However, his current passion lies in AI-driven education and fostering\", \"score\": 0.8443195, \"raw_content\": null}, {\"title\": \"The Professional Journey of Andrej Karpathy - Perplexity\", \"url\": \"https://www.perplexity.ai/page/the-professional-journey-of-an-OvR1nmNIQNS5gJPAtPMk5w\", \"content\": \"Andrej Karpathy's association with OpenAI has been marked by two distinct periods of involvement, each contributing significantly to the organization's development in artificial intelligence. Initially joining as one of the founding members, Karpathy played a pivotal role in the early stages of OpenAI, helping to establish its reputation as a\", \"score\": 0.7407191, \"raw_content\": null}], \"response_time\": 1.74}\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search\n",
      "\n",
      "{\"query\": \"What are some of Andrej Karpathy's most influential projects or publications?\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"title\": \"Andrej Karpathy: The 100 Most Influential People in AI 2024 - TIME\", \"url\": \"https://time.com/7012851/andrej-karpathy/\", \"content\": \"Andrej Karpathy’s name is strewn across the history of modern AI. In 2015, Karpathy, alongside his colleague Professor Fei-Fei Li, designed Stanford University’s first course dedicated to deep-learning, for which he was the primary instructor. “I’m a little bit obsessed with coming to the core of things, ” Karpathy says. His latest venture, Eureka Labs, founded July 2024, aims to build a school that is “AI native.” Its first product will be an undergraduate-level course on AI, designed by a human and guided by an AI teaching assistant. When he first built his AI course at Stanford nine years ago, he was working part-time, and it was done over a few months. Buy your copy of the TIME100 AI issue here\", \"score\": 0.70483154, \"raw_content\": null}, {\"title\": \"Andrej Karpathy's research works | Stanford University, CA (SU) and ...\", \"url\": \"https://www.researchgate.net/scientific-contributions/Andrej-Karpathy-70761057\", \"content\": \"Andrej Karpathy's 14 research works with 53,299 citations and 32,220 reads, including: PixelCNN++: Improving the PixelCNN with Discretized Logistic Mixture Likelihood and Other Modifications\", \"score\": 0.62633044, \"raw_content\": null}, {\"title\": \"‪Andrej Karpathy‬ - ‪Google Scholar‬\", \"url\": \"https://scholar.google.com/citations?user=l8WuQJgAAAAJ&hl=en\", \"content\": \"Andrej Karpathy. Computer Science PhD student, Stanford University. Verified email at cs.stanford.edu - Homepage. Machine Learning Computer Vision Artificial Intelligence. ... A Karpathy, S Miller, L Fei-Fei. 2013 IEEE International Conference on Robotics and Automation, 2088-2095, 2013. 230:\", \"score\": 0.5654673, \"raw_content\": null}, {\"title\": \"Unlock Genius: Dive Into Andrej Karpathy's Top 8 Mind ... - Medium\", \"url\": \"https://medium.com/@Reviewbooks/unlock-genius-dive-into-andrej-karpathys-top-8-mind-blowing-book-picks-7458dcbef3b1\", \"content\": \"Why is Andrej Karpathy so famous? Andrej Karpathy has gained widespread recognition for his significant contributions to the field of artificial intelligence (AI), particularly in the development\", \"score\": 0.49538648, \"raw_content\": null}, {\"title\": \"Andrej Karpathy\", \"url\": \"https://karpathy.ai/\", \"content\": \"2024 - I started Eureka Labs, a new AI+Education company. Meanwhile, I also make educational videos on AI on my YouTube channel. General audience track: Deep Dive into LLMs like ChatGPT is on under-the hood fundamentals of LLMs. 2017 - 2022 I was the Sr. Director of AI at Tesla, where I led the computer vision team of Tesla Autopilot. This includes in-house data labeling, neural network training, the science of making it work, and deployment in production running on our custom inference chip.\", \"score\": 0.40967003, \"raw_content\": null}], \"response_time\": 2.13}\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "检索完毕\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "# Andrej Karpathy: AI Visionary and Innovator\n",
      "\n",
      "## Who is Andrej Karpathy?\n",
      "\n",
      "Andrej Karpathy is a leading figure in artificial intelligence and machine learning, known for his significant contributions to deep learning, computer vision, and autonomous systems. Born in Bratislava (now Slovakia), he moved to Toronto at age 15 and completed his education in computer science and physics at the University of Toronto, followed by a master's at the University of British Columbia and a PhD at Stanford University under AI pioneer Fei-Fei Li.\n",
      "\n",
      "## Notable Contributions\n",
      "\n",
      "Karpathy has made several groundbreaking contributions to AI:\n",
      "\n",
      "- **Convolutional Neural Networks (CNNs)**: Worked on advancing this cornerstone technology in computer vision during his PhD\n",
      "- **Image Captioning**: Developed AI systems capable of generating descriptive text for images\n",
      "- **Deep Learning Education**: Co-designed Stanford University's first deep learning course in 2015 with Fei-Fei Li\n",
      "- **Autonomous Vehicles**: Advanced Tesla's Autopilot capabilities through deep neural networks\n",
      "\n",
      "## Professional Roles\n",
      "\n",
      "Karpathy has held key positions at major technology companies:\n",
      "\n",
      "- **OpenAI**: \n",
      "  - Co-founded OpenAI and specialized in deep learning and computer vision\n",
      "  - Returned in 2023 to lead a team improving GPT-4 and ChatGPT\n",
      "- **Tesla**: \n",
      "  - Served as Senior Director of AI (2017-2022)\n",
      "  - Led Tesla's computer vision team for Autopilot\n",
      "  - Oversaw in-house data labeling, neural network training, and production deployment\n",
      "\n",
      "## Influential Projects and Publications\n",
      "\n",
      "Karpathy's most impactful work includes:\n",
      "\n",
      "- **Stanford's Deep Learning Course**: Pioneering curriculum that educated thousands in AI\n",
      "- **PixelCNN++**: Improved image generation model with discretized logistic mixture likelihood\n",
      "- **Autonomous Driving Systems**: Developed Tesla's vision-based self-driving technology\n",
      "- **Eureka Labs**: His newest venture (founded 2024) creating AI-native education solutions\n",
      "\n",
      "With over 53,000 citations for his research works, Karpathy continues to shape the AI field through both technical innovation and education. His current focus includes AI-driven learning platforms that combine human expertise with AI teaching assistants.\n"
     ]
    }
   ],
   "source": [
    "for item in output[\"messages\"]:\n",
    "    item.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 170,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "帮我写一个 chaofa 的个人生平\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "```json\n",
      "{\n",
      "    \"questions\": [\n",
      "        \"Who is Chaofa and what are their notable achievements?\",\n",
      "        \"What are the key events in Chaofa's life?\",\n",
      "        \"How has Chaofa contributed to their field or society?\"\n",
      "    ]\n",
      "}\n",
      "```\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "以下是根据搜索结果整理的关于“Chaofa”的个人生平信息：\n",
      "\n",
      "---\n",
      "\n",
      "### **Chaofa 的生平与成就**\n",
      "\n",
      "1. **Zhang Chaofa（张朝发）**  \n",
      "   - **背景**：张朝发是中国清朝时期的一位将领，活跃于鸦片战争期间。  \n",
      "   - **关键事件**：  \n",
      "     - 在鸦片战争中，张朝发率领军队与英军作战，并在战斗中表现出色。  \n",
      "     - 在一次战斗中，他利用敌军船只漏水的机会追击并取得胜利，因此被连续三次晋升，最终成为总兵（高级将领）。  \n",
      "     - 然而，在定海失守后，朝廷调查责任时，张朝发被错误指控为战败的罪魁祸首，最终被处决。  \n",
      "   - **贡献**：他的英勇作战和牺牲精神在鸦片战争中留下了深刻的印记。\n",
      "\n",
      "2. **Hmong ChaoFa（苗族王国）**  \n",
      "   - **背景**：Hmong ChaoFa 是一个致力于为老挝苗族人民争取自决权的组织。  \n",
      "   - **关键事件**：  \n",
      "     - 1998年，Hmong ChaoFa 通过了宪法，并开始为苗族人民的权利和自由奋斗。  \n",
      "     - 该组织的领导人因其在冲突解决和受压迫人民权利方面的贡献，获得了荷兰政府的骑士称号。  \n",
      "   - **贡献**：Hmong ChaoFa 在国际社会中为苗族人民的权益发声，并致力于和平与自决。\n",
      "\n",
      "3. **Wei Chaofa（魏朝发）**  \n",
      "   - **背景**：魏朝发是一位艺术家，其作品和生平在 MutualArt 等艺术平台上有记录。  \n",
      "   - **贡献**：他的艺术创作可能对当代艺术领域有所影响，但具体成就需进一步查阅。\n",
      "\n",
      "4. **Biography Chaofa（传记潮发）**  \n",
      "   - **背景**：这是一个专注于食品安全的牛肉火锅品牌，拥有自己的牛养殖基地和分销链。  \n",
      "   - **贡献**：通过严格控制食品安全，为消费者提供高质量的食品。\n",
      "\n",
      "---\n",
      "\n",
      "### 总结\n",
      "“Chaofa”这一名称可能指代不同的人物或组织，包括历史人物张朝发、苗族权利组织 Hmong ChaoFa、艺术家魏朝发或商业品牌传记潮发。如果您需要更具体的信息，请提供更多背景或明确所指的对象。\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "以下是关于不同领域\"Chaofa\"的详细生平报告整理：\n",
      "\n",
      "一、历史人物：张朝发（清代抗英将领）\n",
      "1. 军事生涯\n",
      "- 鸦片战争时期清军将领\n",
      "- 在定海保卫战中指挥作战\n",
      "- 曾利用敌军战船漏水时机成功追击获胜\n",
      "- 因战功获三次晋升至总兵衔\n",
      "\n",
      "2. 历史事件\n",
      "- 1841年定海失守后被朝廷追责\n",
      "- 遭钦差大臣诬陷承担战败责任\n",
      "- 最终被冤判斩首\n",
      "- 成为鸦片战争首位殉国的高级将领\n",
      "\n",
      "3. 历史评价\n",
      "- 体现晚清军人气节\n",
      "- 其冤案反映清朝军政体系弊端\n",
      "- 现被视为民族气节象征人物\n",
      "\n",
      "二、社会组织：Hmong ChaoFa（老挝苗族权益组织）\n",
      "1. 成立发展\n",
      "- 1998年正式成立并颁布宪法\n",
      "- 致力于老挝苗族民族自决运动\n",
      "- 2018年加入UNPO（无代表国家与民族组织）\n",
      "\n",
      "2. 主要活动\n",
      "- 争取苗族政治权利\n",
      "- 反对老挝政府土地侵占政策\n",
      "- 建立海外联络网络\n",
      "- 领导人获荷兰政府骑士勋章\n",
      "\n",
      "3. 现状挑战\n",
      "- 成员常遭老挝军方打击\n",
      "- 2018年遭遇军事袭击造成伤亡\n",
      "- 持续受到老挝政府压制\n",
      "\n",
      "三、商业品牌：传记潮发（餐饮企业）\n",
      "1. 经营特色\n",
      "- 宁夏自有肉牛养殖基地\n",
      "- 广州至宁夏全程冷链配送\n",
      "- 主打高端牛肉火锅市场\n",
      "- 实现从牧场到餐桌全链条管控\n",
      "\n",
      "2. 企业理念\n",
      "- 严格食品安全标准\n",
      "- 主打优质秦川牛肉\n",
      "- 建立自有物流团队\n",
      "- 强调食材可追溯体系\n",
      "\n",
      "四、其他相关人物\n",
      "1. 魏朝发\n",
      "- 当代艺术家\n",
      "- 作品见于MutualArt等平台\n",
      "- 具体艺术成就需进一步考证\n",
      "\n",
      "注：由于\"Chaofa\"对应多个实体，本报告已分类整理。如需特定对象的深入资料，建议提供更明确的指向信息。历史人物张朝发部分基于清代战史记载，社会组织部分依据国际NGO档案，企业信息来自商业报道。\n"
     ]
    }
   ],
   "source": [
    "events = app.stream(\n",
    "    {\"messages\": [{\"role\": \"user\", \"content\": \"帮我写一个 chaofa 的个人生平\"}]},\n",
    "    config,\n",
    "    stream_mode=\"values\",\n",
    ")\n",
    "for event in events:\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'x': '123'}"
      ]
     },
     "execution_count": 183,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "\n",
    "\n",
    "class A(BaseModel):\n",
    "    x: str = Field(default=\"123\", description=\"this is for x\")\n",
    "\n",
    "ins = A()\n",
    "ins.model_dump()"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
